﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace CommonNet48.Encrypt
{
    /// <summary>
    /// AES加密解密帮助类
    /// </summary>
    public class AESHelper
    {
        /// <summary>
        /// 获取AES加密有效密码(要求密码长度必需为32个字节)。
        /// </summary>
        /// <param name="keySour">传入的原始密码</param>
        /// <returns></returns>
        private static string GetValidKey(string keySour)
        {
            decimal baseLen = 32;
            if (keySour.Length < baseLen)
            {
                return string.Empty;
            }
            else
            {
                int len = Convert.ToInt32(baseLen * Math.Floor(keySour.Length / baseLen));
                return keySour.Substring(0, len);
            }
        }


        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str">明文(待加密)</param>
        /// <param name="key">加密Key(长度必需为32字节)</param>
        /// <returns>加密后的密文</returns>
        public static string Encrypt(string str, string key = "Aa6666668888888888888888666666zZ")
        {
            string strKey = GetValidKey(key);
            if (strKey.Length == 0)
            {
                throw new Exception("加密Key不符合规范，无法加密！");
            }
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(strKey),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">密文(待解密)</param>
        /// <param name="key">解密Key(长度必需为32字节)</param>
        /// <returns>解密后的明文</returns>
        public static string Decrypt(string str, string key= "Aa6666668888888888888888666666zZ")
        {
            string strKey = GetValidKey(key);
            if (strKey.Length == 0)
            {
                throw new Exception("解密Key不符合规范，无法加密！");
            }
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
    }
}
